//
//  DAFileUploadTableViewCell.m
//  DAKnowledge
//
//  Created by DreamArts on 16/7/12.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DAFileUploadTableViewCell.h"
#import "DALabel.h"
#import "DACommentView.h"
#import "DACommentButton.h"
#import "DAHomePageTimeLineModel.h"
#import "UIImageView+WebCache.h"
#import "DAHeader.h"
#import "Utility.h"
#import "UAProgressView.h"
#import "DADownloadFile.h"

@interface DAFileUploadTableViewCell ()
@property (weak, nonatomic) IBOutlet UIImageView *UserImageView;
@property (weak, nonatomic) IBOutlet UILabel *timeline;
@property (weak, nonatomic) IBOutlet UIView *statsBackView;
@property (weak, nonatomic) IBOutlet UIImageView *stateImageView;
@property (weak, nonatomic) IBOutlet DALabel *userNameLabel;
@property (weak, nonatomic) IBOutlet DALabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIImageView *bookImageView;
@property (weak, nonatomic) IBOutlet DALabel *fileNameLabel;
@property (weak, nonatomic) IBOutlet DALabel *fileSizeLabel;
@property (nonatomic) BOOL isExist;
@property (weak, nonatomic) IBOutlet UILabel *downloadStatusLabel;
@property (weak, nonatomic) IBOutlet UILabel *middleLabel;
@property (nonatomic, assign) BOOL isDownloading;

@end

@implementation DAFileUploadTableViewCell

- (void)awakeFromNib {
    // Initialization code
    
    // 注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAllStatus) name:@"CHANGEALLSTATUS" object:nil];
}

- (void)setModel:(DAHomePageTimeLineModel *)model{
    _model = model;
    // 头像
    [self.UserImageView sd_setImageWithURL:[NSURL URLWithString:model.userFace] placeholderImage:[UIImage imageNamed:@"holderface"] options:SDWebImageRefreshCached];
    self.UserImageView.layer.cornerRadius = 3;
    self.UserImageView.clipsToBounds = YES;
    self.UserImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *userFaceImageTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickUserFaceImage:)];
    [self.UserImageView addGestureRecognizer:userFaceImageTap];
    
    // 用户名
    NSString *userName = model.userName;
    [self.userNameLabel setText:userName fitToContent:YES];
    self.userNameLabel.textColor = [UIColor colorWithHexString:bookNameColor];
    // 时间轴颜色
    self.timeline.backgroundColor = [UIColor colorWithHexString:timeLineColor];
    // 时间
    NSString *string = NSLocalizedString(@"uploaded", nil);
    self.timeLabel.text = [NSString stringWithFormat:@"%@ %@", model.timelineDate,string];
    self.timeLabel.textColor = [UIColor colorWithHexString:timeColor];
    // 状态图片
    self.stateImageView.image = [UIImage imageNamed:@"file_icon"];
    self.stateImageView.layer.cornerRadius = 10;
    self.statsBackView.layer.cornerRadius = 10;
    // #6EB8EC  #FFF039
    self.statsBackView.backgroundColor = [UIColor colorWithHexString:@"#6EB8EC"];
    
//    // 占位图
//    UIView *bookCover = [[UIView alloc]initWithFrame:CGRectMake(0 , 0, self.bookImageView.frame.size.width, self.bookImageView.frame.size.height)];
//    bookCover.backgroundColor = [UIColor supportGreenColor];
//    DALabel *bookCoverName = [[DALabel alloc]initWithFrame:CGRectMake(5, 5, bookCover.frame.size.width -10, bookCover.frame.size.height - 10)];
//    [bookCoverName setText:model.bookName fitToContent:YES];
//    bookCoverName.verticalAlignment = VerticalAlignmentMiddle;
//    bookCoverName.textAlignment = NSTextAlignmentCenter;
//    [bookCoverName setTextColor:[UIColor whiteColor]];
//    bookCoverName.font = [UIFont systemFontOfSize:12];
//    [bookCover addSubview:bookCoverName];
//    
//    UIImage *image = [self makeImageWithView:bookCover];
//    // 图书 图片
//    [self.bookImageView sd_setImageWithURL:[NSURL URLWithString:model.bookImage] placeholderImage:image];
//    [self.bookImageView.layer setBorderColor:[UIColor whiteColor].CGColor];
//    [self.bookImageView.layer setBorderWidth:3];
     NSString *file = [NSString stringWithFormat:@"file_%@.png",model.timelinefileExtend];
    UIImage *image = [UIImage imageNamed:file];
    self.bookImageView.image = image;
    self.bookImageView.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickImage:)];
    [self.bookImageView addGestureRecognizer:tap];
    
    [self.fileNameLabel setText:model.timelineMessage fitToContent:YES];
    self.fileNameLabel.verticalAlignment = VerticalAlignmentTop;
    self.fileNameLabel.textColor = [UIColor colorWithHexString:bookNameColor];
    
    self.fileSizeLabel.font = [UIFont systemFontOfSize:12];
  //  [self.fileSizeLabel setText:[self calculateTheFileSize:model.timelinefileSize] fitToContent:YES];
    self.fileSizeLabel.text = [self calculateTheFileSize:model.timelinefileSize];
    self.fileSizeLabel.textColor = [UIColor colorWithHexString:borrowTimeColor];
    NSLog(@"%@ %@", model.timelineMessage,[self calculateTheFileSize:model.timelinefileSize]);    
    //self.downloadStatusLabel.textColor = [UIColor colorWithHexString:borrowTimeColor];
    self.downloadStatusLabel.font = [UIFont systemFontOfSize:12];
    self.downloadStatusLabel.numberOfLines = 0;
    
    if (model.isReplyCommentAllShow) {
        self.commentView.sumHeight = model.rowHeight;
    }else{
        self.commentView.sumHeight = model.beforeTenRowHeight;
    }
    self.commentView.heightArray = model.replyHeightArray;
    self.commentView.isShowAllReply = model.isReplyCommentAllShow;
    self.commentView.isClickMoreDataButton = YES;
    [self.commentView transferCommetArray:model.replyArray indexPath:self.cellIndexPath];
    
    // 进度条
    self.progressView.layer.cornerRadius = 26;
    self.progressView.backgroundColor = [UIColor whiteColor];
    self.progressView.tintColor = [UIColor whiteColor];
    [self.progressView bringSubviewToFront:self.bookImageView];
   // [self.progressView bringSubviewToFront:self.bookImageView];
    
    BOOL isExist = [self isFileExist:[NSString stringWithFormat:@"%@.%@", model.timelinefolderName, model.timelinefileExtend]];
    self.isExist = isExist;
    [self changeDownloadSatutsWithIsExist:isExist];
 
}
- (void)setCellIndexPath:(NSIndexPath *)cellIndexPath{
    if (_cellIndexPath != cellIndexPath) {
        _cellIndexPath = cellIndexPath;
    }
}

#pragma mark - 判断沙盒里是否有这个文件
-(BOOL)isFileExist:(NSString *)fileName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    //  NSLog(@"该文件：%@",result?@"有！！":@"不存在");
    return result;
}

#pragma mark - 计算文件大小
- (NSString *)calculateTheFileSize:(NSString *)size{
    int fileSize = size.intValue;
    NSString *strSize;
    float fileSizeK = 0.0;
    float fileSizeM = 0.0;
    if (fileSize > 999 && fileSize < 999 * 1024) {
        fileSizeK = fileSize / 1024.0;
        strSize = [NSString stringWithFormat:@"%.2fK", fileSizeK];
    }else if (fileSize >= 999 * 1024){
        fileSizeM = fileSize / (1024 * 1024);
        strSize = [NSString stringWithFormat:@"%.2fM", fileSizeM];
    }else{
        strSize = [NSString stringWithFormat:@"%dB", fileSize];
    }
    return strSize;
}
#pragma mark - 点击图片的手势方法
- (void)clickImage:(UITapGestureRecognizer *)tap{
     BOOL isExist = [self isFileExist:[NSString stringWithFormat:@"%@.%@", self.model.timelinefolderName, self.model.timelinefileExtend]];
    [self changeDownloadSatutsWithIsExist:isExist];
    
    if (self.isDownloading) {
        NSLog(@"文件正在下载");
    }else{
        if (isExist) {
            [self.delegate clickFileImageWithModel:self.model];
        }else{
            [DADownloadFile downloadFileWithPath:self.model.timelinefileurl fileFolderName:self.model.timelinefolderName FileExtend:self.model.timelinefileExtend block:^(CGFloat count) {
                [self.progressView setProgress:count];
                self.progressView.tintColor = [UIColor supportGreenColor];
                self.isDownloading = YES;
            } commpleteBlock:^{
                self.progressView.tintColor = [UIColor whiteColor];
                NSString *str = NSLocalizedString(@"isDownloadingSuccessful", nil);
                self.downloadStatusLabel.text = str;
                self.downloadStatusLabel.textColor = [UIColor supportGreenColor];
                self.isExist = YES;
                self.isDownloading = NO;
            }  ];
        }
    }
}
#pragma mark - 根据本地文件是否存在 来改变文字状态
- (void)changeDownloadSatutsWithIsExist:(BOOL) isExist{
    NSString *downloadSuccessfulStr = NSLocalizedString(@"isDownloadingSuccessful", nil);
    NSString *notDownloadStr = NSLocalizedString(@"NotDownload", nil);
    if (isExist) {
        self.downloadStatusLabel.text = downloadSuccessfulStr;
        self.downloadStatusLabel.textColor = [UIColor supportGreenColor];
    }else{
        self.downloadStatusLabel.text = notDownloadStr;
        self.downloadStatusLabel.textColor = [UIColor colorWithHexString:borrowTimeColor];
    }
}
#pragma mark - 点击头像手势方法
- (void)clickUserFaceImage:(UITapGestureRecognizer *)tap{
    [self.delegate clickFileUserFaceImageWith:self.model];
    
}

#pragma mark - 清除缓存时 发出的通知
- (void)changeAllStatus{
    NSString *notDownloadStr = NSLocalizedString(@"NotDownload", nil);
    self.downloadStatusLabel.text = notDownloadStr;
    self.downloadStatusLabel.textColor = [UIColor colorWithHexString:borrowTimeColor];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
